<template>
  <div class="rby-bg">
    <el-dialog
      title="扣图/修改"
      :visible.sync="isDialogVisible"
      append-to-body
      :close-on-click-modal="false"
      @close="close"
    >
      <el-form :model="removeBgForm">
        <el-form-item v-if="removeBgForm.url !== ''" label="图片">
          <el-image
            style="width: 100px; height: 100px"
            :src="removeBgForm.url"
            :preview-src-list="[removeBgForm.url]"
          />
          <el-image
            v-if="this.removeBgForm.mask !== ''"
            style="width: 100px; height: 100px"
            :src="removeBgForm.mask"
            :preview-src-list="[removeBgForm.mask]"
          />
          <el-button type="primary" size="mini" :loading="getsizeloading" @click="onBtn">{{ editimage_text }}</el-button>
          <el-button v-if="removeBgForm.mask.length" type="danger" size="mini" @click="removeBgForm.mask=''">清除mask</el-button>
          <el-alert
            v-if="this.removeBgForm.mask.length"
            title="修改的部位mask已经生成，最终图片需要 点击【提交处理】去除选择部位"
            type="success"
            effect="dark"
          />
          <el-input v-model="removeBgForm.url" />
        </el-form-item>
        <el-form-item v-if="removeBgForm.urls.length && removeBgForm.mask ===''" label="图片列表">
          <el-image
            v-for="item in removeBgForm.urls"
            :key="item"
            style="width: 100px; height: 100px"
            fit="fill"
            :src="item"
            :preview-src-list="[item]"
            @dblclick="handleRemove"
          />
        </el-form-item>
        <el-form-item label="local产品ID">
          <el-input v-model="removeBgForm.product_id" autocomplete="off" />
        </el-form-item>
        <el-form-item label="服务商">
          <el-select v-model="removeBgForm.service" placeholder="服务商" size="small" filterable clearable>
            <el-option
              v-for="item in removebgServices"
              :key="item.value"
              :label="item.value"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item v-if="removeBgForm.mask ===''" label="图片格式">
          <el-select v-model="removeBgForm.format" placeholder="图片格式" size="small" filterable clearable>
            <el-option value="jpg" label="jpg" />
            <el-option value="png" label="png" />
          </el-select>
        </el-form-item>
        <el-form-item v-if="removeBgForm.mask ===''" label="背景色">
          <el-color-picker v-model="removeBgForm.bg_color" />
        </el-form-item>
        <el-form-item label="存储">
          <el-select v-model="removeBgForm.save_type" placeholder="图片存储" size="small" filterable clearable>
            <el-option value="s3" label="s3" />
            <el-option value="erp" label="erp" />
          </el-select>
        </el-form-item>
        <el-form-item label="立即处理">
          <el-switch
            v-model="removeBgForm.sync"
            active-color="#13ce66"
            inactive-color="#ff4949"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="isDialogVisible=false">取 消</el-button>
        <el-button type="primary" :loading="removeBgProcessing" @click="handleAddRemoveBg">提交处理</el-button>
      </div>
    </el-dialog>
    <el-dialog
      title="绘制需要修改的地方"
      :visible.sync="centerDialogVisible"
      :fullscreen="true"
      @close="handleEditImageClose"
    >
      <div
        v-if="this.getsizeloading"
        v-loading="getsizeloading"
        element-loading-spinner="el-icon-loading"
        element-loading-background="rgba(0, 0, 0, 0.8)"
        element-loading-text="获取图片尺寸中..."
      >
        <img :src="removeBgForm.url">
      </div>

      <remove-pic-watermark
        ref="watermark"
        @maskEnd="onMaskEnd"
      />
      <span slot="footer" class="dialog-footer">
        <el-button @click="centerDialogVisible = false">取 消</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { Post as Addremovebgimage, GetImageSize } from '@/api/erp/removebgimages'
import Cookies from 'js-cookie'

export default {
  name: 'RemoveBg',
  components: {
    RemovePicWatermark: () => import('@/components/RemovePicWatermark/Index')
  },
  props: ['url', 'urls', 'product_id', 'sync', 'isVisible'],
  data() {
    return {
      editimage_text: '精确修图',
      getsizeloading: false,
      centerDialogVisible: false,
      isDialogVisible: false,
      selected_image_list: [],
      removeBgProcessing: false,
      removeBgVisible: false,
      removebgServices: [
        { value: 'picwish' },
        { value: 'remove.bg' }
      ],
      imagesizes: [],
      usemask: false,
      removeBgForm: {
        sync: false,
        save_type: 's3',
        url: '',
        urls: [],
        product_id: '',
        service: 'picwish',
        bg_color: '#ffffff',
        format: 'jpg',
        mask: ''
      }
    }
  },
  watch: {
    isVisible(v) {
      this.isDialogVisible = v
      if (v) {
        this.removeBgForm.url = this.url
        this.removeBgForm.urls = this.urls
        this.removeBgForm.product_id = this.product_id
        this.removeBgForm.sync = this.sync
      } else {
        this.removeBgForm.url = ''
        this.removeBgForm.urls = []
        this.removeBgForm.product_id = ''
        this.removeBgForm.sync = false
      }
    }
  },
  created() {
    this.removeBgForm.save_type = Cookies.get('remove-bg-save-type') || 's3'
  },
  methods: {
    handleEditImageClose() {
      this.editimage_text = '精确修图'
      this.$refs.watermark.claenData()
    },
    makeImageJson() {
      if (this.removeBgForm.url.length === 0) {
        this.$message.error('没有图片url')
        return false
      }
      this.getsizeloading = true
      this.centerDialogVisible = true
      this.editimage_text = '获取图片尺寸中...'
      let j = null
      for (let i = 0; i < this.imagesizes.length; i++) {
        if (this.imagesizes[i].imgUrl === this.removeBgForm.url) {
          j = this.imagesizes[i]
          break
        }
      }
      if (j) {
        console.log('useing local size')
        this.getsizeloading = false
        this.$refs.watermark.onMaskStart(j)
      } else {
        GetImageSize({ url: this.removeBgForm.url }).then(response => {
          j = { imgUrl: this.removeBgForm.url, width: response.size.width, height: response.size.height }
          console.log(j)
          this.imagesizes.push(j)
          this.getsizeloading = false
          this.$refs.watermark.onMaskStart(j)
        }).catch(err => {
          this.$message.error('添加失败:' + err)
          this.getsizeloading = false
          return false
        })
      }
    },
    deleteMask() {
      this.removeBgForm.mask = ''
    },
    onBtn() {
      this.mask = null
      this.makeImageJson()
    },
    onMaskEnd(data) {
      this.centerDialogVisible = false
      this.removeBgForm.mask = data.maskBase64
      this.$message.success('成功')
      this.json = ''
    },
    handleChangeMethod() {
      if (!this.usemask) {
        this.removeBgForm.mask = ''
      }
    },
    handleRemove(v) {
      const url = v.toElement.currentSrc
      const exist_urls = []
      if (url) {
        for (let i = 0; i < this.removeBgForm.urls.length; i++) {
          if (this.removeBgForm.urls[i] !== url) {
            exist_urls.push(this.removeBgForm.urls[i])
          }
        }
        this.removeBgForm.urls = exist_urls
      }
    },
    handleAddRemoveBg() {
      this.removeBgProcessing = true
      Addremovebgimage(this.removeBgForm).then(response => {
        this.$emit('success', response.data.data)
        Cookies.set('remove-bg-save-type', this.removeBgForm.save_type)
        this.removeBgForm.urls = []
        this.removeBgForm.mask = ''
        this.selected_image_list = []
        this.removeBgVisible = false
        this.removeBgProcessing = false
        this.close()
      }).catch(err => {
        this.this.$message.success('添加失败:' + err)
        this.removeBgProcessing = false
        this.removeBgVisible = false
      })
    },
    close() {
      this.removeBgProcessing = false
      this.removeBgForm.mask = ''
      this.removeBgForm.urls = []
      this.removeBgForm.url = ''
      this.$emit('close', false)
    }
  }
}
</script>

<style scoped>
  .el-tag + .el-tag {
    margin-left: 10px;
  }

  .top >>> .el-select .el-input {
    width: 350px;
  }

  .top >>> .input-with-select .el-input-group__prepend {
    background-color: #fff;
  }

  .top {
    padding-left: 20px;
    margin-bottom: 30px;
    margin-top: 28px;
  }

  .input-with-select {
    width: calc(100% - 200px);
  }

  .add-btn {
    float: right;
    margin-right: 20px;
    width: 150px
  }

  .mt-pagination {
    float: right;
    margin-top: 5px;
  }

  .app-container >>> .el-dialog {
    margin-top: 48px !important;
    margin-bottom: 68px;
  }

  .rby-bg >>> .el-dialog.is-fullscreen {
    width: 100%;
    margin-top: 0;
    margin-bottom: 0;
    height: 100%;
    overflow: hidden;
}

  .mt-dialog >>> .el-transfer-panel {
    width: calc(50% - 60px);
  }

  .mt-form >>> .el-select {
    width: 100%;
  }

  .mt-form >>> .el-input__inner {
    width: 100%;
  }

  .mt-dialog >>> .el-dialog {
    margin-top: 60px;
    /*margin: 168px auto !important;*/
  }

  .mt-dialog >>> .el-dialog__body {
    padding-bottom: 100px;
  }
</style>
